package icbc.app.control
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	import icbc.app.AppGlobal;
	
	public class SegListItem extends Sprite
	{
		private static const FONT_COLOR:uint = 0xffffff;
		private static const TEXT_POSX:uint = 30;
		private static const ICON_WIDTH:uint = 39;
		private static const TEXT_HEIGHT:uint = 27;
		private var gap:uint = 5;
		private var data:Object;
		private var controlWidth:uint;
		private var controlHeight:uint;
		private var icon:Sprite;
		
		private var panel:Sprite;
		
		public function SegListItem(data:Object, vWidth:uint, vHeight:uint)
		{
			super();
			this.data = data;
			this.controlWidth = vWidth;
			this.controlHeight = vHeight;
			addEventListener(Event.ADDED_TO_STAGE, initStage);
		}
		
		private function initStage(evt:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, initStage);
			initContent();
		}

		private function initContent():void
		{
			panel = buildPanel();
			addChild(panel);
			
			icon = new Sprite();
			panel.addChild(icon);
			icon.x = gap;

			var txt:TextField = buildItemText(data.label);
			panel.addChild(txt);
			txt.x = icon.x + ICON_WIDTH + 10;
			txt.y = panel.height/2 - txt.textHeight/2;
			
			buildIcon();
		}

		private function buildPanel():Sprite
		{
			var background:Sprite = new Sprite();
			background.graphics.beginFill(0xDD82ED,0);
			background.graphics.drawRoundRect(0,0, controlWidth, controlHeight, 10, 10);
			background.graphics.endFill();
			return background;
		}

		private function buildItemText(text:String):TextField
		{
			var format:TextFormat = new TextFormat();
			format.font = AppGlobal.FONT_NAME;
			format.color = FONT_COLOR;
			format.size = 16;
			format.bold = true;
			var txt:TextField = new TextField();
			txt.selectable = false;
			txt.width = controlWidth - gap*2 - ICON_WIDTH;
			txt.height = TEXT_HEIGHT;
			txt.defaultTextFormat = format;
			txt.text = text;
			return txt;
		}
		
		private function buildIcon():void
		{
			if(data.icon == null || data.icon == "")
			{
				return;
			}
			var iconPath:String = data.icon;
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.load(new URLRequest(iconPath));
			icon.addChild(loader);
		}

		private function onIOError(evt:IOErrorEvent):void
		{
			trace("SegListitem.Image["+ data.icon +"].IOError: "+ evt.text);
		}		

		private function imageComplete(evt:Event):void
		{
			var image:DisplayObject = (evt.target as LoaderInfo).content;
			icon.y = controlHeight/2 - image.height/2;
		}
	}
}